package top.jle.spring.basic.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.CallbackException;
import org.hibernate.Interceptor;
import org.hibernate.type.Type;
import top.jle.jpa.basic.entities.TimeMarkedEntity;
import top.jle.jpa.basic.entities.UnDeletableEntity;

import java.util.Map;
import java.util.function.UnaryOperator;

@Slf4j
public class EntityInterceptor implements Interceptor {

    public EntityInterceptor() {
        log.info("EntityInterceptor init");
    }

    private static final Map<String, UnaryOperator<Object>> PROPERTY_HANDLE_MAP = Map.of(
            TimeMarkedEntity.PROP_CREATE_TIME,
            o-> o==null?System.currentTimeMillis():o,
            TimeMarkedEntity.PROP_LAST_MODIFY_TIME,
            o->o==null?System.currentTimeMillis():o,
            UnDeletableEntity.PROP_STATUS,
            o->{
                if(!Integer.valueOf(UnDeletableEntity.STATUS_INVALID).equals(o)){
                    o = UnDeletableEntity.STATUS_VALID;
                }
                return o;
            }
    );


    @Override
    public boolean onSave(Object entity, Object id, Object[] state, String[] propertyNames, Type[] types) {
        for(int i=0;i<propertyNames.length;i++){
            UnaryOperator<Object> c = PROPERTY_HANDLE_MAP.get(propertyNames[i]);
            if(c!=null){
                state[i] = c.apply(state[i]);
            }
        }
        return true;
    }

    @Override
    public boolean onFlushDirty(Object entity, Object id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
        for(int i=0;i<currentState.length;i++){
            if(currentState[i]==null){
                continue;
            }
            UnaryOperator<Object> c = PROPERTY_HANDLE_MAP.get(propertyNames[i]);
            if(c!=null){
                currentState[i] = c.apply(currentState[i]);
            }
        }
        return true;
    }
}